var form, table, tableInstance;

$(function () {
    loadFileType();
    initLayUI(function () {
        initButtons();
    })
});

function initLayUI(cb) {
    layui.use(['table', 'form'], function () {
        table = layui.table;
        form = layui.form;

        form.render();

        tableInstance = table.render({
            elem: '#fileTable',
            limits: [10, 15, 20],
            url: ServerURL + "/file/list",
            headers: tokenUtil.getAuthHeader(),
            method: "POST",
            toolbar: '#toolbar',
            cols: [[
                {field: 'fileId', title: '文件编号', align: 'center', minWidth: 50},
                {field: 'fileName', title: '文件名称', align: 'center', minWidth: 100},
                {
                    field: 'fileSize', title: '文件大小(MB)', align: 'center', minWidth: 100
                },
                {field: 'fileType', title: '文件类型', align: 'center', minWidth: 100},
                {field: 'createTime', title: '创建时间', align: 'center', minWidth: 100},
                {field: 'oper', title: '操作', minWidth: 300, align: 'center', toolbar: "#operBar"}
            ]],
            contentType: 'application/json',
            response: {
                statusName: 'code',
                statusCode: 200,
                msgName: 'msg',
                countName: 'count',
                dataName: 'data'
            },
            loading: true,
            page: true,
            error: function (res) {
                ajaxUtil.handleError(res);
            },

        });

        table.on('tool(fileTable)', function (obj) {
            if (obj.event === 'delete') {
                deleteFile(obj);
            } else if (obj.event === 'download') {
                downloadFile(obj);
            }
        });

        cb();
    });
}


function initButtons() {
    $("#searchBtn").click(function () {
        reloadTable();
    });

    $("#resetBtn").click(function () {
        form.val('form', {
            "fileName": "",
            "fileType": ""
        });
        reloadTable();
    });
}

function reloadTable() {
    let data = form.val('form');
    tableInstance.reload({
        where: data,
        page: {
            curr: 1
        }
    });
}

function deleteFile(obj) {
    layerUtil.confirm("确定要删除该文件么?", function () {
        ajaxUtil.simplePost({
            "fileId": obj.data.fileId
        }, "/file/delete", function () {
            reloadTable();
        });
    });
}

function downloadFile(obj) {
    window.open(ServerURL + "/file/download?fileId=" + obj.data.fileId + "&rf-auth=" + tokenUtil.getToken(), "_blank");
}

function loadFileType() {
    ajaxUtil.loadDict("sys_file_type", function (data) {
        data.forEach(function (item) {
            $("#fileType").append("<option value='" + item.dictValue + "' >" + item.dictLabel + "</option>");
        });
        form.render();
    })
}